using System;

namespace SG3L_RAG.Domain.Entities
{
    public class DocumentChunk : EntityBase
    {
        public Guid DocumentId { get; private set; }
        public Document? Document { get; private set; }
        public int ChunkIndex { get; private set; }
        public string Content { get; private set; } = string.Empty;
        public float[] Vector { get; private set; } = Array.Empty<float>();

        // EF Core 需要的无参构造函数
        public DocumentChunk() { }

        // 业务构造函数
        private DocumentChunk(Guid documentId, int chunkIndex, string content, float[] vector)
        {
            DocumentId = documentId;
            ChunkIndex = chunkIndex;
            Content = content;
            Vector = vector;
            CreatedAt = DateTime.UtcNow;
        }

        // 工厂方法
        public static DocumentChunk Create(Guid documentId, int chunkIndex, string content, float[] vector)
        {
            return new DocumentChunk(documentId, chunkIndex, content, vector);
        }

        // 业务方法
        public void UpdateVector(float[] vector)
        {
            Vector = vector;
            UpdatedAt = DateTime.UtcNow;
        }

        public bool IsEmpty() => string.IsNullOrWhiteSpace(Content);

        // 计算与其他向量的余弦相似度
        public float CosineSimilarity(float[] otherVector)
        {
            if (Vector == null || otherVector == null || Vector.Length != otherVector.Length) return 0f;
            float dot = 0, normA = 0, normB = 0;
            for (int i = 0; i < Vector.Length; i++)
            {
                dot += Vector[i] * otherVector[i];
                normA += Vector[i] * Vector[i];
                normB += otherVector[i] * otherVector[i];
            }
            return dot / (float)(Math.Sqrt(normA) * Math.Sqrt(normB) + 1e-8);
        }
    }
}
